package com.fubowen.lepton.ui.base

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.fubowen.lepton.conf.SiteConfigViewModel
import com.fubowen.lepton.extension.isNotNull
import com.fubowen.lepton.helper.ViewHelper.dpToPx
import com.fubowen.lepton.theme.ThemeViewModel
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.launch


const val PERCENT_HEIGHT = "percentHeight"

open class ThemeDialogFragment : BottomSheetDialogFragment() {

    private val mSiteViewModel: SiteConfigViewModel by activityViewModels()
    private val mThemeViewModel: ThemeViewModel by activityViewModels()
    private var mTheme = 0
    private var mHeight = 0f
    private val mBottomSheetId = com.google.android.material.R.id.design_bottom_sheet

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.apply {
            mHeight = getFloat(PERCENT_HEIGHT)
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bsd = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        bsd.behavior.state = BottomSheetBehavior.STATE_EXPANDED
        return bsd
    }

    override fun onStart() {
        super.onStart()
        setPercentHeight()
        setBackground()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        observeTheme()
    }

    private fun setPercentHeight() {
        if (mHeight != 0f) {
            val screenHeight = resources.displayMetrics.heightPixels
            val h = (screenHeight * mHeight).toInt()
            requireView().updateLayoutParams<ViewGroup.MarginLayoutParams> {
                height = h
            }
        }
    }

    private fun setBackground() {
        GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(Color.TRANSPARENT)
            cornerRadius = requireContext().dpToPx(8).toFloat()
            dialog?.findViewById<FrameLayout>(mBottomSheetId)?.background = this
        }
    }

    //region observeTheme
    private fun observeTheme() = lifecycleScope.launch {
        mThemeViewModel.themeFlow.collect {
            if (view.isNotNull()) {
                mThemeViewModel.setViewTheme(requireView())
            }
        }
    }
    //endregion
}